<template>
	<div class="todo-container">
		<div class="todo-wrap">
			<Add v-bind:addTodo="addTodo"/>
			<List v-bind:todos="todos" v-bind:delTodo="delTodo"/>
			<Lower>
				<input type="checkbox" v-model="isAll" slot="checkAll"/>
				<span slot="count">已完成{{completeSize}} / 全部{{todos.length}}</span>
				<button slot="btn" class="btn btn-danger" @click="delComplete" v-show="completeSize > 0">清除已完成任务</button>
			</Lower>
		</div>
  </div>
</template>

<script>
	import Add from './components/Add.vue'
	import List from './components/List.vue'
	import Lower from './components/Lower.vue'
	export default {
		components:{
			Add, List, Lower
		},
		// 定义数组
		data() {
			return{
				/* 
				*  数据的存储：从localStorage读取数据
				*/
				todos:JSON.parse(window.localStorage.getItem("todos_key") || '[]')
			}
		},
		computed:{
			// 已完成的数量使用vue的计算属性写起来更简单写
			completeSize() {
				return this.todos.reduce((preTotal, todo) => preTotal + (todo.flog?1:0), 0);
			},
			isAll:{
				get() {
					// 已完成的 为勾选的 ，勾选的等价于数组全部的数量，则该值返回true，否则返回false
					return this.completeSize === this.todos.length && this.completeSize > 0;
				},
				set(value) {
					// value为当前checkbox的最新的值
					this.allExe(value);
				}
			}
		},
		methods:{
			addTodo(obj) {
				this.todos.unshift(obj);
			},
			delTodo(index) {
				this.todos.splice(index, 1);
			},
			// 删除所有已完成的任务
			delComplete() {
				// 1. 过滤数组，仅保留flog为true的数据传递过去即可
				const newTodos = this.todos.filter(todo => !todo.flog);
				if(window.confirm("确定要清除已完成的" + (this.todos.length - newTodos.length) + "个任务么？")) {
					this.todos = newTodos;
				}
			},
			// 全选全部选函数
			allExe(check) {
				this.todos.forEach(todo => todo.flog = check);
			}
		},
		
		watch:{ // 监听
			todos:{
				deep:true, //开启深度监听
				handler:function(value){
					// 将todos最新的值的JSON数据，保存到localStorage中去
					window.localStorage.setItem("todos_key", JSON.stringify(value));
				}
			}
		}
	}
</script>

<style>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
